import $ from 'jquery';

export class Component {
    constructor(container, options = {}) {
        this.container = $(container);
        this.options = options;
        this.cid = this.generateCID();
        this.events = {};
        this.name = '默认'
    }

    generateCID() {
        return `component-${Math.random().toString(36).substr(2, 9)}`;
    }

    getDefaultOptions() {
        return {};
    }

    bindDOMEvent(element, event, handler) {
        const boundHandler = handler.bind(this);
        $(element).on(event, boundHandler);

        const key = `${element}-${event}`;
        if (!this._boundEvents.has(key)) {
            this._boundEvents.set(key, []);
        }
        this._boundEvents.get(key).push({ element, event, handler: boundHandler });
    }

    init() {
        // 子类实现
    }

    render() {
        // 子类实现
    }

    on(event, callback) {
        if (!this.events[event]) this.events[event] = [];
        this.events[event].push(callback);
        return this;
    }

    trigger(event, ...args) {
        if (this.events[event]) {
            this.events[event].forEach(callback => callback.apply(this, args));
        }
        return this;
    }

    /**
   * 解绑事件
   * @param {string} [event] - 事件名，不传则解绑所有事件
   * @param {Function} [callback] - 回调函数，不传则解绑该事件下所有回调
   */
    off(event, callback) {
        if (!event) {
            this.events = {};
            return this;
        }

        if (!this.events[event]) return this;

        if (!callback) {
            delete this.events[event];
            return this;
        }

        this.events[event] = this.events[event].filter(cb => cb !== callback);

        return this;
    }

    destroy() {
        // 清理事件和DOM
        this.events = {};
        if (this.container && typeof this.container.empty === 'function') {
            this.container.empty();
        }
    }
}